<template>
  <!-- action="/api/common/filesUpload.php" -->

  <a-upload
    name="avatar"
    list-type="picture-card"
    class="avatar-uploader"
    :show-upload-list="false"
    :before-upload="beforeUpload"
    @change="handleChange"
    method="post"
    :customRequest="Upload"
  >
    <img v-if="imageUrl" :src="imageUrl" alt="avatar" width="400" height="400" />
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
      <div class="ant-upload-text">上传头像</div>
    </div>
  </a-upload>
</template>
<script>
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default {
  data() {
    return {
      loading: false,
      imageUrl: "",
    };
  },
  methods: {
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        getBase64(info.file.originFileObj, (imageUrl) => {
          this.imageUrl = imageUrl;
          this.loading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    async Upload(e) {
      console.log(e.file);
      let formData = new FormData();
      formData.append("file", e.file);
      //   this.$axios({
      //       url:"/api/common/filesUpload.php",
      //       method:'post',
      //       data:formData,
      //     //   processData: false,// 告诉axios不要去处理发送的数据(重要参数)
      //     //   contentType: false,   // 告诉axios不要去设置Content-Type请求头
      //   })
      //     .then((res) => {
      //       console.log(res);
      //     });
      let res = await this.$uploading.upload(formData); //图片上传
      this.imageUrl = res.data.data.url;
      this.loading = false;
      this.$emit("on-change", this.imageUrl);
    },
  },
};
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
